from sqlalchemy.orm import Session

from app.models.attr_group_rel import AttrGroupRelDo
from app.models.attribute import AttributeDo
from app.models.attribute_group import AttributeGroupDo
from app.schemas.attribute import AttributeGroupBo, AttributeBo, AttributeVo


def query_att_by_category_id(db: Session, category_id: int) -> list[AttributeVo]:
    """根据分类查询属性"""
    category_do_list = db.query(AttributeDo).filter(AttributeDo.category_id == category_id).all()
    return [AttributeVo.model_validate(b) for b in category_do_list]


def att_group_modify(db: Session, att_group: AttributeGroupBo) -> bool:
    """新增or修改属性分组"""
    if att_group.attr_group_id:
        group_do = db.query(AttributeGroupDo).filter(AttributeGroupDo.id == att_group.attr_group_id).one()
        for key, value in att_group.model_dump(exclude_unset=True).items():
            setattr(group_do, key, value)
        db.commit()
        db.refresh(group_do)
        return True
    brand_db = AttributeGroupDo(**att_group.model_dump())
    db.add(brand_db)
    db.commit()
    db.refresh(brand_db)
    return True


def att_modify(db: Session, att: AttributeBo) -> bool:
    """新增or修改属性"""
    if att.attr_id:
        att = db.query(AttributeDo).filter(AttributeDo.id == att.attr_id).one()
        for key, value in att.model_dump(exclude_unset=True).items():
            setattr(att, key, value)
        db.commit()
        return True
    att_db = AttributeDo(**att.model_dump(exclude={"attr_id", "attr_group_id"}))
    db.add(att_db)
    db.flush()  
    # 关联关系
    att_group_rel_modify(db, att_db.attr_id, att.attr_group_id)
    db.commit()
    return True


def att_group_rel_modify(db: Session, att_id: int, att_group_id: int) -> bool:
    """关联关系"""
    (db.query(AttrGroupRelDo).filter(AttrGroupRelDo.attr_group_id == att_group_id)
     .filter(AttrGroupRelDo.attr_id == att_id).delete())
    save_db = AttrGroupRelDo(attr_group_id=att_group_id, attr_id=att_id)
    db.add(save_db)
